package org.example.gametalk.gameTalkUtils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Date;
public class JwtUtils {
    private final static String secret = "This_is_a_secret_key_for_token_and_need_to_a_long_string";
    private final static SecretKey key = Keys.hmacShaKeyFor(secret.getBytes());
    private static final long expirationTime=60*60*24*7;
    //获取一个token
    public  static String getToken(Integer userId){
        return Jwts.builder().header().type("jwt").add("alg",key.getAlgorithm()).and()
                .claim("userId", userId)
                .expiration(new Date(System.currentTimeMillis()+expirationTime))
                .signWith(key)
                .compact();
    }

    //测试用:获取一个其他类型key的token
    public static String getBadToken(Integer userId){
        return Jwts.builder().header().type("jwt").add("alg",key.getAlgorithm()).and()
                .claim("userId", userId)
                .expiration(new Date(System.currentTimeMillis()+expirationTime))
                .signWith(Keys.hmacShaKeyFor("This_is_A_test_token_for_my_token_test".getBytes()))
                .compact();
    }

    //测试用:获取一个已经过期的token
    public static String getExpiredToken(Integer userId){
        return Jwts.builder().header().type("jwt").add("alg",key.getAlgorithm()).and()
                .claim("userId", userId)
                .expiration(new Date(System.currentTimeMillis()))
                .signWith(key)
                .compact();
    }

    /**验证token
     * 1.验证token是否合法
     * 2.验证token是否超时
     * */
    public static boolean verifyToken(String token){
        try{
            Jwts.parser().verifyWith(key).build().parseSignedClaims(token);
        }catch (Exception e){
            //这里有好几种错误可以捕捉
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //获取userId
    //TODO 全局统一异常管理
    public static Integer getUserIdFromToken(String token)throws Exception{
        try {
            Claims payload = Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload();
            return (Integer) payload.get("userId");
        }catch (Exception e){
            throw new RuntimeException();
        }
    }







}
